package org.future.persistent.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

/**
 * 连接工具
 * @author  
 * @date    2010-6-18
 * @file    org.demo.dao.datasource.ConnectionTools.java
 */
public abstract class ConnectionTools {
	// 数据源工厂
	protected static DataSourceFactory _factory;
	static {
		try {
			_factory = new PropertyDataSourceFactory();
		} catch(IOException e){
			e.printStackTrace();
		}
	}
	/**
	 * 返回默认数据源的连接
	 * @return  connection or null
	 */
	public static Connection getConnection(){
		return getConnection(DataSourceFactory.defaultDataSourceName);
	}
	/**
	 * 返回指定数据源的连接
	 * @param dataSourceName
	 *        The dataSource name
	 * @return  connection or null
	 */
	public static Connection getConnection(String dataSourceName){
		DataSource datasource = _factory.getDataSource(dataSourceName);
		Connection conn = null;
		if(datasource != null){
			try{
				conn = datasource.getConnection();
			} catch (SQLException e){
				e.printStackTrace();
			}
		}
		return conn;
	}
	/**
	 * 关闭连接对象
	 * @param rset
	 * 		  ResultSet
	 * @param stmt
	 *        Statement
	 * @param conn
	 *        Connection
	 */
	public static void close(ResultSet rset,Statement stmt,Connection conn){
		try { if (rset != null) rset.close(); } catch (Exception e) {}
		try { if (stmt != null) stmt.close(); } catch (Exception e) {}
		try { if (conn != null) conn.close(); } catch (Exception e) {}
	}
}
